package com.hy.mvc.web.conroller;

import com.alibaba.fastjson.JSON;
import com.hy.mvc.biz.utils.IPUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.ModelMap;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * <pre>
 *    author  : Booker
 *    time    : 2017/12/4 16:58
 *    desc    : 输入描述
 *    version : v1.0
 * </pre>
 */
public abstract class BaseController {
    /**
     * 错误信息变量名定义 此处与页面上不一致，故意不在页面上显示错误信息
     * 以方便用户去选择其它酒店
     */
    public static final String ERR_MSG = "error_msg";
    /****
     * 服务器信息。
     */
    public static final String HOST_INFO = "_iphv_";
    protected final static String JSON_RESULT = "screen/json";
    protected final static String ERR_PAGE = "/error.vm";  // 统一出错页面
    protected static final String RATE_SERVICCE_QUERY_RATE = "110";  // 查询rate 失败
    protected static final String RATE_SERVICCE_UPDATE_RATE = "120";  // 更新rate 失败
    protected static final String RATEPLAN_CHECK_PRICE = "130";  // 更新rate 失败
    protected static final int CANCEL_POLICY_TYPE_BEFORE_HOUR = 5; // 从入住当天24点往前推算，提前多少小时能退

    protected static final String SUCCESS_ACTION_CODE = "200";  // 更新rate 成功
    protected static final String FAILURE_ACTION_CODE = "130";  // 更新rate 失败
    protected static final String DOMAIN_NAME_ADDRESS = "http://hotel.fliggy.com";
    protected static final String DOMAIN_DAILY_NAME_ADDRESS = "http://hotel.daily.alitrip.net";

    protected static final String WEEK_INDEX_SEPARATOR = "\\,";
    protected static final String LOG_GROUP_SEPARATOR = ",";
    protected static final int NUMBER_OF_ONE_WEEK = 7;

    /**
     * tbToken
     */
    private static final String DEFAULT_TOKEN_KEY = "_tb_token_";
    protected final String EXCEPTION_PARAMS_ERROR = "100";  // 参数不正确
    /**
     * logger
     */
    protected Logger logger = LoggerFactory.getLogger(BaseController.class);

    /**
     * forward json格式结果
     * 注意errorMsg与Msg的区别
     *
     * @param modelMap
     * @param callback
     * @param isSuccess
     * @param data
     * @param errCode
     * @param errMsg
     * @param tbToken
     */
    protected <T> String createJsonResult(ModelMap modelMap, String callback, boolean isSuccess, T data, String errCode,
                                          String errMsg, String tbToken) {

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("ret", isSuccess);
        map.put("errorCode", StringUtils.trimToEmpty(errCode));
        map.put("errorMsg", StringUtils.trimToEmpty(errMsg));
        map.put("Msg", StringUtils.trimToEmpty(errMsg));
        map.put("data", data);
        map.put(DEFAULT_TOKEN_KEY, StringUtils.trimToEmpty(tbToken));
        map.put(HOST_INFO, IPUtils.getHostInfo());
        String json = "";
        try {
            json = JSON.toJSONString(map);
        } catch (Exception e) {
            logger.error("", e);
        }
        modelMap.put("json", this.assembleCallback(callback, json));
        return JSON_RESULT;

    }

    /**
     * 解决jsonp的回调函数问题
     *
     * @param callback
     * @param json
     * @return
     */
    protected String assembleCallback(String callback, String json) {

        callback = org.apache.commons.lang.StringUtils.trimToNull(callback);
        if (callback != null) {
            // 做过滤
            //callback = TBStringUtil.escapeHTML(callback);
            callback = StringEscapeUtils.escapeHtml4(callback); // 做过滤 冲突的时候选择我这个
            return callback + "(" + json + ")";
        }
        return json;

    }

    /**
     * 图片上传失败后回调的error页面
     *
     * @param modelMap
     * @param callback
     * @param error
     * @return
     */
    protected String forwardToError(ModelMap modelMap, String callback, String error) {

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("status", "0");
        map.put("message", error);

        String json = JSON.toJSONString(map);

        modelMap.put("json", this.assembleCallback(callback, json));

        return JSON_RESULT;
    }

    /**
     * 图片上传成功后回调的success页面
     *
     * @param modelMap
     * @param callback
     * @param filename
     * @param tfsKey
     * @param url
     * @return
     */
    protected String forwardToSuccess(ModelMap modelMap, String callback, String filename, String tfsKey, String url) {

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("status", "1");
        map.put("type", "ajax");
        try {
            map.put("name", new String(filename.getBytes(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            logger.error("文件名转码失败, 原因: 遇到异常, {0}", e);
        }
        map.put("tfsKey", tfsKey);
        map.put("url", url);

        String json = JSON.toJSONString(map);

        modelMap.put("json", this.assembleCallback(callback, json));

        return JSON_RESULT;
    }


    /**
     * 构造结果
     *
     * @param modelMap
     * @param callback
     * @param isSuccess
     * @param data
     * @param errCode
     * @param errMsg
     * @param tbToken
     * @param <T>
     */
    protected <T> void buildJsonResult(ModelMap modelMap, String callback, boolean isSuccess, T data, String errCode, String errMsg, String tbToken) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("ret", isSuccess);
        map.put("errorCode", StringUtils.trimToEmpty(errCode));
        map.put("errorMsg", StringUtils.trimToEmpty(errMsg));
        map.put("data", data);
//        map.put(CsrfTokenForWeb3.DEFAULT_TOKEN_KEY, StringUtils.trimToEmpty(tbToken));
        map.put(HOST_INFO, IPUtils.getHostInfo());
        String json = "";
        try {
            json = JSON.toJSONString(map);
        } catch (Exception e) {
            logger.error("", e);
        }
        modelMap.put("json", this.assembleCallback(callback, json));
    }

    /**
     * 构造失败结果(简洁版)
     *
     * @param modelMap
     * @param errMsg
     */
    protected void buildResultFail(ModelMap modelMap, String errorCode, String errMsg, String callback) {
        forwardToJson(modelMap, callback, false, null, errorCode, errMsg);
    }


    protected <T> String forwardToJson(ModelMap model, String callback, boolean isSuccess, T data, String errCode, String errMsg) {
        Map<String, Object> map = new HashMap<>();
        map.put("ret", isSuccess);
        map.put("errorCode", org.apache.commons.lang.StringUtils.trimToEmpty(errCode));
        map.put("msg", org.apache.commons.lang.StringUtils.trimToEmpty(errMsg));
        map.put("data", data);
        map.put(HOST_INFO, IPUtils.getHostInfo());
        String json = "";
        try {
            json = JSON.toJSONString(map);
        } catch (Exception e) {
            logger.error("", e);
        }
        json = this.assembleCallback(callback, json);
        model.put("json", json);
        return JSON_RESULT;
    }


    /**
     * forward json格式结果
     *
     * @param modelMap
     * @param callback
     * @param isSuccess
     * @param data
     * @param errCode
     * @param errMsg
     * @param tbToken
     */
    protected <T> String createJsonResultWithMsgAndErrorCode(ModelMap modelMap, String callback, boolean isSuccess, T data, String errCode, String errMsg, String tbToken) {

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("ret", isSuccess);
        map.put("data", data);
        map.put("msg", StringUtils.trimToEmpty(errMsg));
        map.put("errorCode", StringUtils.trimToEmpty(errCode));
        map.put(HOST_INFO, IPUtils.getHostInfo());

        String json = "";
        try {
            json = JSON.toJSONString(map);
        } catch (Exception e) {
            logger.error("", e);
        }
        modelMap.put("json", this.assembleCallback(callback, json));
        return JSON_RESULT;
    }

    /**
     * forward json格式结果
     *
     * @param modelMap
     * @param callback
     * @param isSuccess
     * @param data
     * @param errCode
     * @param errMsg
     * @param tbToken
     */
    protected <T> String createJsonResultWithMsgAndCode(ModelMap modelMap, String callback, boolean isSuccess, T data, String errCode, String errMsg, String tbToken) {

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("ret", isSuccess);
        map.put("data", data);
        map.put("msg", StringUtils.trimToEmpty(errMsg));
        map.put("code", StringUtils.trimToEmpty(errCode));
        map.put(HOST_INFO, IPUtils.getHostInfo());

        String json = "";
        try {
            json = JSON.toJSONString(map);
        } catch (Exception e) {
            logger.error("", e);
        }
        modelMap.put("json", this.assembleCallback(callback, json));
        return JSON_RESULT;
    }


}
